// 账号管理功能脚本

// 页面加载完成后执行
// 不使用新的DOMContentLoaded事件监听器，避免与HTML中的冲突
console.log('账号管理脚本加载完成');

// 确保在DOM内容加载完成后执行
console.log('account-management.js文件已加载，准备执行loadAccounts()');

// 直接调用loadAccounts()函数
loadAccounts();

// 加载账号列表
async function loadAccounts() {
    console.log('========================================');
    console.log('开始执行loadAccounts()函数 - 时间戳:', new Date().toISOString());

    // 检查页面上的所有元素
    console.log('页面元素检查:');
    console.log('document.body exists:', !!document.body);
    console.log('document.body children count:', document.body.children.length);

    // 尝试多种选择器查找容器
    const containers = [
        document.querySelector('.grid.grid-cols-1'),
        document.querySelector('.grid'),
        document.querySelector('.account-list-container')
    ];

    containers.forEach((container, index) => {
        console.log(`容器 ${index + 1}:`, container);
    });

    // 使用第一个找到的容器
    let accountListContainer = containers.find(c => c);

    if (!accountListContainer) {
        // 如果没有找到容器，创建一个
        console.error('未找到账号列表容器，创建一个临时容器');
        accountListContainer = document.createElement('div');
        accountListContainer.className = 'account-list-container';
        document.body.appendChild(accountListContainer);
    }

    console.log('最终使用的容器元素:', accountListContainer);

    // 直接尝试发送请求获取真实数据
    try {
        console.log('尝试发送请求到/api/accounts (不阻塞UI)');
        const response = await fetch('/api/accounts', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'same-origin'
        });

        console.log('请求完成，响应状态:', response.status);

        // 特别处理401未授权错误
        if (response.status === 401) {
            console.log('收到401未授权错误，提示用户登录');

            // 创建登录提示通知
            const notification = document.createElement('div');
            notification.className = 'fixed top-4 right-4 bg-amber-50 border-l-4 border-amber-500 p-4 shadow-lg z-50';
            notification.innerHTML = `
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fa fa-exclamation-triangle text-amber-500"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-amber-700">需要登录才能查看真实账号数据</p>
                        <button id="loginNotificationBtn" class="mt-2 text-xs bg-primary hover:bg-primary-dark text-white px-3 py-1 rounded transition-colors">
                            去登录
                        </button>
                    </div>
                </div>
            `;
            document.body.appendChild(notification);

            // 绑定登录按钮事件
            document.getElementById('loginNotificationBtn').addEventListener('click', () => {
                // 显示登录模态框或跳转到登录页面
                if (typeof showLoginModal === 'function') {
                    showLoginModal();
                } else {
                    window.location.href = '/login.html';
                }
                notification.remove();
            });

            // 3秒后自动关闭通知
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 5000);
        }

        const data = await response.json();
        console.log('收到响应数据:', JSON.stringify(data));

        // 如果成功获取到真实数据，更新显示
        if (response.ok && data?.data && data.data.length > 0) {
            console.log('收到真实数据，更新UI');
            renderAccounts(data.data);
        }
    } catch (error) {
        console.error('fetch请求失败:', error);

        // 显示错误通知
        const notification = document.createElement('div');
        notification.className = 'fixed top-4 right-4 bg-red-50 border-l-4 border-red-500 p-4 shadow-lg z-50';
        notification.innerHTML = `
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fa fa-exclamation-circle text-red-500"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-red-700">获取账号数据失败: ${error.message}</p>
                    <button id="closeErrorNotification" class="mt-2 text-xs text-gray-500 hover:text-gray-700">
                        关闭
                    </button>
                </div>
            </div>
        `;
        document.body.appendChild(notification);

        // 绑定关闭按钮事件
        document.getElementById('closeErrorNotification').addEventListener('click', () => {
            notification.remove();
        });
    }
}

// 渲染账号列表
function renderAccounts(accounts) {
    // 更新选择器以匹配HTML中的实际结构
    const accountListContainer = document.querySelector('.grid.grid-cols-1');
    if (!accountListContainer) {
        console.error('未找到账号列表容器');
        return;
    }

    if (!accountListContainer) return;

    if (accounts.length === 0) {
        renderEmptyAccounts('您还没有添加任何账号');
        return;
    }

    // 清空容器
    accountListContainer.innerHTML = '';

    // 根据数据库中的账号类型，获取对应的图标和颜色
      const getAccountTypeInfo = (type) => {
          // 确保类型转换为数字，处理字符串类型的type值
          const typeNum = Number(type);
          const typeMap = {
              1: { icon: 'fa-weixin', color: 'bg-green-100 text-green-600', name: '微信' },
              2: { icon: 'fa-music', color: 'bg-red-100 text-red-600', name: '抖音' },
              3: { icon: 'fa-user', color: 'bg-blue-100 text-blue-600', name: '系统账号' },
              4: { icon: 'fa-envelope-o', color: 'bg-yellow-100 text-yellow-600', name: '邮箱' }
          };
          return typeMap[typeNum] || { icon: 'fa-user-circle-o', color: 'bg-gray-100 text-gray-600', name: '其他' };
      };

      // 为每个账号创建卡片
      accounts.forEach(account => {
          // 使用新的数据字段名 accountType
          const typeInfo = getAccountTypeInfo(account.accountType);
          
          // 根据授权状态获取文本和样式
          function getAuthStatusInfo(status, isExpired) {
            // 处理文本类型的status
            if (typeof status === 'string') {
                if (status.includes('已授权') || status.includes('正常')) {
                    return isExpired ? { text: '已授权(已过期)', class: 'bg-yellow-100 text-yellow-800' } : 
                                      { text: status, class: 'bg-green-100 text-green-800' };
                } else if (status.includes('过期')) {
                    return { text: status, class: 'bg-yellow-100 text-yellow-800' };
                } else if (status.includes('取消')) {
                    return { text: status, class: 'bg-red-100 text-red-800' };
                } else {
                    return { text: status || '未知状态', class: 'bg-gray-100 text-gray-800' };
                }
            }
            // 保持对数字状态的兼容
            switch (status) {
                case 1:
                    return isExpired ? { text: '正常授权(已过期)', class: 'bg-yellow-100 text-yellow-800' } : 
                                      { text: '正常授权', class: 'bg-green-100 text-green-800' };
                case 2:
                    return { text: '已过期', class: 'bg-yellow-100 text-yellow-800' };
                case 3:
                    return { text: '已取消', class: 'bg-red-100 text-red-800' };
                default:
                    return { text: '未知状态', class: 'bg-gray-100 text-gray-800' };
            }
        }
        
        const authInfo = getAuthStatusInfo(account.status, account.isExpired);

        const card = document.createElement('div');
        card.className = 'account-card bg-white border border-gray-200 rounded-lg p-4 shadow-sm';
        card.innerHTML = `
            <div class="flex justify-between items-start mb-3">
                <div class="flex items-center">
                    <div class="w-12 h-12 ${typeInfo.color} rounded-full flex items-center justify-center mr-3 border border-gray-300">
                        <i class="fa ${typeInfo.icon} text-2xl"></i>
                    </div>
                    <div>
                        <h4 class="font-semibold text-gray-800">${account.accountName || '未知账号'}</h4>
                        <div class="text-sm text-gray-500">${account.accountId || ''}</div>
                    </div>
                </div>
                <div class="${authInfo.class} text-xs px-2 py-1 rounded-full">
                    ${authInfo.text}
                </div>
            </div>
            <div class="space-y-2 mb-4">
                <div class="text-sm text-gray-600">
                    <i class="fa fa-tag mr-1"></i>
                    <span>${typeInfo.name}</span>
                </div>
                <div class="text-sm text-gray-600">
                    <i class="fa fa-id-card-o mr-1"></i>
                    <span>账号ID: ${account.id || '未知'}</span>
                </div>
                ${account.createdAt ? `
                <div class="text-sm text-gray-600">
                    <i class="fa fa-calendar mr-1"></i>
                    <span>创建时间: ${account.createdAt}</span>
                </div>` : ''}
            </div>
            <div class="flex justify-end space-x-2">
                <button class="text-blue-600 hover:text-blue-800 text-sm" onclick="editAccount(${account.id})">
                    <i class="fa fa-edit mr-1"></i>编辑
                </button>
                <button class="text-green-600 hover:text-green-800 text-sm" onclick="publishWithAccount(${account.id}, '${account.accountName}', ${account.accountType})">
                    <i class="fa fa-paper-plane mr-1"></i>发布
                </button>
                <button class="text-red-600 hover:text-red-800 text-sm" onclick="deleteAccount(${account.id})">
                    <i class="fa fa-trash-o mr-1"></i>删除
                </button>
            </div>
        `;

        accountListContainer.appendChild(card);
    });
}

// 渲染空账号状态
function renderEmptyAccounts(message) {
    // 更新选择器以匹配HTML中的实际结构
    const accountListContainer = document.querySelector('.grid.grid-cols-1');
    if (!accountListContainer) {
        console.error('未找到账号列表容器');
        return;
    }
    if (accountListContainer) {
        accountListContainer.innerHTML = `
            <div class="col-span-full text-center py-12 bg-gray-50 rounded-lg">
                <i class="fa fa-user-circle-o text-4xl text-gray-300 mb-3"></i>
                <p class="text-gray-500 mb-4">${message}</p>
                <button id="addFirstAccountBtn" class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 transition-all">
                    <i class="fa fa-plus mr-2"></i>添加第一个账号
                </button>
            </div>
        `;

        // 添加按钮事件
        document.getElementById('addFirstAccountBtn').addEventListener('click', function () {
            document.getElementById('addAccountBtn').click();
        });
    }
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '';

    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '';

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}

// 编辑账号
function editAccount(accountId) {
    alert('编辑账号功能开发中，账号ID: ' + accountId);
    // 这里将实现编辑账号的逻辑
}

// 重新授权账号功能已删除

// 删除账号
function deleteAccount(accountId) {
    // 使用更友好的确认对话框，明确提示用户操作的后果
    if (confirm('确定要删除这个账号吗？\n\n删除后数据将无法恢复，相关的所有信息都会被永久清除。')) {
        // 显示加载状态
        const button = event.target.closest('button');
        if (button) {
            button.disabled = true;
            button.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i>删除中...';
        }
        
        // 发送删除请求到服务器
        fetch(`/api/accounts/${accountId}`, {
            method: 'DELETE',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                // 恢复按钮状态
                if (button) {
                    button.disabled = false;
                    button.innerHTML = '<i class="fa fa-trash-o mr-1"></i>删除';
                }
                
                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 处理响应数据
                if (data && data.code === 0) {
                    // 删除成功，显示成功通知
                    showNotification('账号删除成功', 'success');
                    // 重新加载账号列表
                    loadAccounts();
                } else {
                    // 删除失败
                    showNotification('账号删除失败: ' + (data?.message || '未知错误'), 'error');
                }
            })
            .catch(error => {
                // 恢复按钮状态
                if (button) {
                    button.disabled = false;
                    button.innerHTML = '<i class="fa fa-trash-o mr-1"></i>删除';
                }
                
                // 捕获异常
                console.error('删除账号失败:', error);
                showNotification('网络错误: ' + error.message + '，请稍后重试', 'error');
            });
    }
}

/**
 * 显示通知消息
 * @param {string} message 通知消息内容
 * @param {string} type 通知类型: 'success', 'error', 'info'
 */
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    
    // 设置通知样式和内容
    let bgColor, borderColor, icon, textColor;
    
    switch(type) {
        case 'success':
            bgColor = 'bg-green-50';
            borderColor = 'border-green-500';
            icon = 'fa-check-circle';
            textColor = 'text-green-700';
            break;
        case 'error':
            bgColor = 'bg-red-50';
            borderColor = 'border-red-500';
            icon = 'fa-exclamation-circle';
            textColor = 'text-red-700';
            break;
        default:
            bgColor = 'bg-blue-50';
            borderColor = 'border-blue-500';
            icon = 'fa-info-circle';
            textColor = 'text-blue-700';
    }
    
    notification.className = `${bgColor} border-l-4 ${borderColor} p-4 shadow-lg z-50 fixed top-4 right-4 transform transition-all duration-300 ease-in-out opacity-0 translate-x-full`;
    notification.innerHTML = `
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fa ${icon} ${textColor} text-xl"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm ${textColor}">${message}</p>
                <button class="mt-2 text-xs ${textColor} hover:underline">
                    关闭
                </button>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.remove('opacity-0', 'translate-x-full');
    }, 100);
    
    // 绑定关闭按钮事件
    notification.querySelector('button').addEventListener('click', () => {
        hideNotification(notification);
    });
    
    // 设置自动关闭
    setTimeout(() => {
        hideNotification(notification);
    }, 5000);
}

/**
 * 隐藏并移除通知
 * @param {HTMLElement} notification 通知元素
 */
function hideNotification(notification) {
    notification.classList.add('opacity-0', 'translate-x-full');
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 300);
}

// 发布功能 - 发送请求到后端API
function publishWithAccount(accountId, accountName, accountType) {
    console.log(`开始使用账号发布: ID=${accountId}, 名称=${accountName}, 类型=${accountType}`);
    
    // 显示加载状态
    const button = event.target.closest('button');
    if (button) {
        button.disabled = true;
        button.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i>发布中...';
    }
    
    // 构建发布数据
    const publishData = {
        account: {
            accountId: accountId,
            accountName: accountName,
            platformType: accountType === 1 ? 'wechat' : 'other' // 根据账号类型设置平台类型
        },
        title: `测试发布-${new Date().toISOString()}`,
        content: `<p>这是一条通过账号 ${accountName} 发送的测试内容</p><p>发布时间: ${new Date().toLocaleString()}</p>`
    };
    
    // 发送发布请求到后端API
    fetch('/api/publish', {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(publishData)
    })
    .then(response => {
        // 恢复按钮状态
        if (button) {
            button.disabled = false;
            button.innerHTML = '<i class="fa fa-paper-plane mr-1"></i>发布';
        }
        
        if (!response.ok) {
            throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('发布响应数据:', data);
        
        if (data && data.success) {
            showNotification(`账号 ${accountName} 发布请求提交成功！任务ID: ${data.taskIds?.join(', ') || '未知'}`, 'success');
        } else {
            showNotification(`发布失败: ${data?.message || '未知错误'}`, 'error');
        }
    })
    .catch(error => {
        // 恢复按钮状态
        if (button) {
            button.disabled = false;
            button.innerHTML = '<i class="fa fa-paper-plane mr-1"></i>发布';
        }
        
        console.error('发布请求失败:', error);
        showNotification(`网络错误: ${error.message}，请稍后重试`, 'error');
    });
}

// 导出函数供其他脚本使用
window.loadAccounts = loadAccounts;
window.publishWithAccount = publishWithAccount;